package cn.jdx.config;

import cn.jdx.entity.Permission;
import cn.jdx.entity.PermissionExample;
import cn.jdx.entity.User;
import cn.jdx.entity.UserExample;
import cn.jdx.service.PermissionServiceImpl;
import cn.jdx.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Resource(name = "permissionServiceImpl")
    private PermissionServiceImpl permissionService;
    @Override
    //(1)授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        //授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");
        //获取用户对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //从用户的id查询权限的名称
        Integer permId = user.getPermId();
        PermissionExample pExample = new PermissionExample();
        pExample.or().andIdEqualTo(permId);
        List<Permission> permissions = permissionService.selectByExample(pExample);
        for (Permission permission : permissions) {
            String permName = permission.getPermName();
            System.out.println("[授权]:"+permName);
            info.addStringPermission(permName);
        }
        return info;//这里之前返回的是null，现在需要返回info
    }

    @Resource(name = "userServiceImpl")
    public UserServiceImpl service;

    @Override
    //(2)认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        //(1)拿到用户名:根据用户名称去查询密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserExample example = new UserExample();
        example.or().andUsernameEqualTo(token.getUsername());
        //(2)获得用户名相同的用户
        List<User> users = service.selectByExample(example);
        //(3)获取密码并且判断
        if (users.size()>0){
            User user = users.get(0);
            String password = user.getPassword();
            System.out.println("[登录]账号="+user.getUsername()+" 密码="+password);
            return new SimpleAuthenticationInfo(user,password,"");
        }else{
            System.out.println("[登录]账号不存在");
            return null;//抛出账号不存在的异常
        }
    }
}
